package com.lpwa.web.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.lpwa.common.annotation.DataSource;
import com.lpwa.common.config.Global;
import com.lpwa.common.config.datasource.DynamicDataSourceContextHolder;
import com.lpwa.common.core.page.*;
import com.lpwa.common.enums.DataSourceType;
import com.lpwa.common.utils.DateUtils;
import com.lpwa.common.utils.RedisUtil;
import com.lpwa.common.utils.StringUtils;
import com.lpwa.common.utils.sql.SqlUtil;
import com.lpwa.system.domain.Tag;
import com.lpwa.system.domain.tagdata.position.TagOne;
import com.lpwa.system.domain.tagdata.position.TagPositiont;
import com.lpwa.system.domain.tagdata.position.Zone;
import com.lpwa.system.mapper.LableMapper;
import com.lpwa.system.mapper.TagDataMapper;
import com.lpwa.system.service.IPersonService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.lpwa.common.annotation.Log;
import com.lpwa.common.enums.BusinessType;
import com.lpwa.system.domain.TagData;
import com.lpwa.system.service.ITagDataService;
import com.lpwa.common.core.controller.BaseController;
import com.lpwa.common.core.domain.AjaxResult;
import com.lpwa.common.utils.poi.ExcelUtil;

/**
 * 标签数据 信息操作处理
 * 
 * @author tanmu
 * @date 2019-06-19
 */
@Controller
@RequestMapping("/system/tagData")
public class TagDataController extends BaseController
{
    private String prefix = "system/tagData";
	
	@Autowired
	private ITagDataService tagDataService;
    @Autowired
    private LableMapper lableMapper;
	@Autowired
	private TagDataMapper tagDataMapper;
	@Autowired
	private IPersonService personService;
	@Autowired
	private RedisUtil redisUtil;
	@RequiresPermissions("system:tagData:view")
	@GetMapping()
	public String tagData()
	{
	    return prefix + "/tagData";
	}
	
	/**
	 * 查询标签数据列表
	 */
	@RequiresPermissions("system:tagData:list")
	@PostMapping("/list")
	@ResponseBody
	@DataSource(value = DataSourceType.SLAVE)
	public TagDataTableDataInfo list(TagData tagData)
	{
		return new TagDataTableDataInfo();
//		try{
//			//查询所有表名
//			DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
//			List<String> tables = tagDataMapper.selectTagDataTables();
//			DynamicDataSourceContextHolder.clearDataSourceType();
//			//分页条件
//			String tableName = tagData.getTableName();//当n前表
//			//获取查询时间
//			String startTime = tagData.getBeginTime();
//			String endTime = tagData.getEndTime();
//			Integer indexer = tagData.getIndex();//索引
//			Integer pageSize = tagData.getPageSize();
//			Integer nowPage = tagData.getNowPage();
//			//如果不为空，则从时间范围内表开始查询
//			if (StringUtils.isNotEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
//				String nowDate = DateUtils.dateTimeNow();//获取当前时间
//				String date = "";
//				//最后一张表通过startTime确定,
//				String endTableDate = DateFormatUtils.format(DateUtils.parseDate(startTime) , "yyyyMMdd");
//				String endTable = "tag_Data_"+endTableDate;
//				//如果endTable表不存在，endTable = tables最后一个元素
//				if (!tables.contains(endTable)){
//					Integer index = tables.size()-1;
//					endTable = tables.get(index);
//				}
//				//为空则判断从那张表开始查询
//				if (StringUtils.isEmpty(tableName)){
//					//将endTime转化为时间格式后与当前时间做对比
//					Date endTimeDate = DateUtils.parseDate(endTime);
//					//如果小于当前时间则tablename=endTime对应的表,否则tablename = nowdate对应的表
//					if (endTimeDate.before(new Date())){
//						tableName ="tag_Data_"+DateFormatUtils.format(DateUtils.parseDate(endTime) , "yyyyMMdd");//(类型转换)
//					}else {
//						date = nowDate.substring(0,8);
//						tableName = "tag_Data_"+date;
//					}
//				}
//				String horizonMaxTable = tableName;
//				String horizonMinTable = endTable;
//				List<TagData> list = new ArrayList<TagData>();
//				//查询时间范围内所有表名-确定需要查询的所有表，参数：horizonMaxTable，horizonMinTable
//				String sql = "SELECT name FROM SysObjects Where XType='U' and name like 'tag_Data%' and name  <>  'tag_Data_yyyyMMdd' and name <='"+horizonMaxTable+"' and name >='"+horizonMinTable+"' order by name desc ";
//				DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
//				List<String> horizonTables =tagDataMapper.selectTagDataHorizonTables(sql);
//				DynamicDataSourceContextHolder.clearDataSourceType();
//				if (StringUtils.isEmpty(horizonTables)){
//					return getTagDataDataTable(list,null,1,0,null);
//				}
//				Integer index = 0;
//				if (indexer!=null){
//					tagData.setTableName(horizonTables.get(indexer));
//					index = indexer;
//				}else {
//					tagData.setTableName(horizonTables.get(index));
//				}
//				Boolean bool = true;
//				//根据表名查询标签历史数据，如果查出数据为空则继续查询下一张表数据，直到有数据为止或者查询的表不存在
//				do {
//					if (nowPage!=null&&pageSize!=null){
//						startPage(pageSize,nowPage);
//						DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
//						list = tagDataService.selectTagDataList(tagData);
//						DynamicDataSourceContextHolder.clearDataSourceType();
//						if (list.size()>0){
//							tableName = tagData.getTableName();
//							bool = false;
//						}else {
//							index=index+1;
//							nowPage=1;//重置页码
//							if (index>=horizonTables.size()){
//								bool = false;
//							}else {
//								tagData.setTableName(horizonTables.get(index));
//							}
//						}
//					}
//				}while (bool);
//				List<String> dataList = new ArrayList<String>();
//				for (String tab:horizonTables){
//					String str =tab.substring(9,17);
//					dataList.add(str);
//				}
//				return getTagDataDataTable(list,tagData.getTableName(),nowPage,index,dataList);
//
//			}else {
//				String date = "";
//				//为空则重第一张表开始查询 第一张表为当天的数据表
//				String nowDate = DateUtils.dateTimeNow();
//				date = nowDate.substring(0,8);
//				tableName = "tag_Data_"+date;
//				String horizonMaxTable = tableName;
//				List<TagData> list = new ArrayList<TagData>();
//				//查询时间范围内所有表名-确定需要查询的所有表，参数：horizonMaxTable，horizonMinTable
//				String sql = "SELECT name FROM SysObjects Where XType='U' and name like 'tag_Data%' and name  <>  'tag_Data_yyyyMMdd' and name <='"+horizonMaxTable+"' order by name desc ";
//				DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
//				List<String> horizonTables =tagDataMapper.selectTagDataHorizonTables(sql);
//				DynamicDataSourceContextHolder.clearDataSourceType();
//				Integer index = 0;
//				if (indexer!=null){
//					tagData.setTableName(horizonTables.get(indexer));
//					index = indexer;
//				}else {
//					tagData.setTableName(horizonTables.get(index));
//				}
//				//根据表名查询标签历史数据，如果查出数据为空则继续查询下一张表数据，直到有数据为止或者查询的表不存在
//				Boolean bool = true;
//				do {
//					if (nowPage!=null&&pageSize!=null){
//						startPage(pageSize,nowPage);
//						DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
//						list = tagDataService.selectTagDataList(tagData);
//						DynamicDataSourceContextHolder.clearDataSourceType();
//						if (list.size()>0){
//							tableName = tagData.getTableName();
//							bool = false;
//						}else {
//							index=index+1;
//							nowPage=1;//重置页码
//							if (index>=horizonTables.size()){
//								bool = false;
//							}else {
//								tagData.setTableName(horizonTables.get(index));
//							}
//						}
//					}
//				}while (bool);
//				List<String> dataList = new ArrayList<String>();
//				for (String tab:horizonTables){
//					String str =tab.substring(9,17);
//					dataList.add(str);
//				}
//				return getTagDataDataTable(list,tagData.getTableName(),nowPage,index,dataList);
//			}
//		}catch (Exception e){
//			return getTagDataDataTable(null,null,1,1,null);
//		}


	}
	public List<TagData> getTagDataByTableName(TagData tagData){
		List<TagData> list = tagDataService.selectTagDataList(tagData);
		return list;
	}

	/*
	 *校验标签是否存在
	 * @Param tagId
	 */
	public Boolean checkIsExistTag(String tagId){
		Tag tag = lableMapper.selectLableById(tagId);
		if (StringUtils.isNull(tag)){
			return false;
		}
		return true;
	}
	/**
	 * 导出标签数据列表
	 */
	@RequiresPermissions("system:tagData:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TagData tagData)
    {
    	List<TagData> list = tagDataService.excelTagDataList(tagData);
        ExcelUtil<TagData> util = new ExcelUtil<TagData>(TagData.class);
        return util.exportExcel(list, "tagData");
    }
	
	/**
	 * 新增标签数据
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存标签数据
	 */
	@RequiresPermissions("system:tagData:add")
	@Log(title = "标签数据", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(TagData tagData)
	{		
		return toAjax(tagDataService.insertTagData(tagData));
	}

	/**
	 * 修改标签数据
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		TagData tagData = tagDataService.selectTagDataById(id);
		mmap.put("tagData", tagData);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存标签数据
	 */
	@RequiresPermissions("system:tagData:edit")
	@Log(title = "标签数据", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(TagData tagData)
	{		
		return toAjax(tagDataService.updateTagData(tagData));
	}
	
	/**
	 * 删除标签数据
	 */
	@RequiresPermissions("system:tagData:remove")
	@Log(title = "标签数据", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(tagDataService.deleteTagDataByIds(ids));
	}
	/**
	 * 设置请求分页数据
	 */
	protected void startPage(Integer pageSize,Integer pageNum)
	{
		PageDomain pageDomain = TableSupport.buildPageRequest();
//		Integer pageNum = pageNum;
//		Integer pageSize = pageSize;
		if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
		{
			String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
			PageHelper.startPage(pageNum, pageSize, orderBy);
		}
	}
	/**
	 * 根据具体时间查询标签数据，轨迹回放功能
	 */
	@RequiresPermissions("system:tagData:track")
	@PostMapping( "/track")
	@ResponseBody
	@DataSource(value = DataSourceType.SLAVE)
	public AjaxResult track(TagData tagData)
	{
		String tagId = tagData.getTagId();
		String startTime = tagData.getBeginTime();
//		String endTime = tagData.getEndTime();
		//根据startTime判断要查找哪一张表数据
		String startTimeDate = DateFormatUtils.format(DateUtils.parseDate(startTime) , "yyyyMMdd");
		String tableName = "tag_Data_"+startTimeDate;
//		String date = startTime.substring(0,8);
//		String tableName = "tag_Data_"+date;
		//根据表名和标签ID和时间查询数据
		TagData t = new TagData();
//		t.setCreateTime(DateUtils.parseDate(startTime));
		t.setBeginTime(startTime);
		t.setEndTime(tagData.getEndTime());
		t.setTableName(tableName);
		t.setTagId(tagId);
		List<TagData> tagDataList = tagDataService.selectTagDataListByTableName(t);
		TagPositiont tagPositiont = transTdmp(tagDataList);
		return AjaxResult.success(tagPositiont);
	}
	public TagPositiont transTdmp(List<TagData> tagDataList){
		if (!StringUtils.isEmpty(tagDataList)){
			TagData tagData = tagDataList.get(0);
			BigDecimal x = tagData.getX();
			BigDecimal y = tagData.getY();
			BigDecimal z = tagData.getZ();
			List<TagOne> listTagOne = new ArrayList<TagOne>();
			List<BigDecimal> position = new ArrayList<BigDecimal>();
			position.add(x);
			position.add(y);
			position.add(z);
			TagPositiont tagPositiont = new TagPositiont();
			TagOne tagOne = new TagOne();
			String coordinateSystemId = Global.getCoordinateSystemId();
			tagOne.setCoordinateSystemId(coordinateSystemId);
			tagOne.setId(tagData.getTagId());
			tagOne.setPositionTS(new Date().getTime());
			tagOne.setSmoothedPosition(position);
			tagOne.setZones(new ArrayList<Zone>());
			listTagOne.add(tagOne);
			tagPositiont.setTags(listTagOne);
			tagPositiont.setResponseTS(new Date().getTime());
			tagPositiont.setVersion("2.1");
			return tagPositiont;
		}else {
			List<TagOne> listTagOne = new ArrayList<TagOne>();
			TagPositiont tagPositiont = new TagPositiont();
			tagPositiont.setTags(listTagOne);
			tagPositiont.setResponseTS(new Date().getTime());
			tagPositiont.setVersion("2.1");
			return tagPositiont;
		}
	}
}
